package com.xyh.transaction.schedule;

import com.alibaba.fastjson.JSONArray;
import com.meilisearch.sdk.exceptions.MeilisearchException;
import com.xyh.transaction.entity.Goods;
import com.xyh.transaction.entity.vo.GoodsVo;
import com.xyh.transaction.listener.MapGoodsImageEvent;
import com.xyh.transaction.mapper.CategoryMapper;
import com.xyh.transaction.mapper.GoodsMapper;
import com.xyh.transaction.mapper.UserMapper;
import com.xyh.transaction.utils.MappingUtil;
import com.xyh.transaction.utils.MeiliSearchUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Configuration
@EnableScheduling
public class GoodsMeilisearchScheduler {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private MeiliSearchUtil meiliSearchUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Value("${meilisearch.enabled}")
    private boolean meiliSearchEnabled;


    @Scheduled(cron = "0 30 0 * * ?")
    public void addGoodsToMeilisearch() throws MeilisearchException {

        if (!meiliSearchEnabled){
            log.info("MeiliSearch未启用，跳过同步");
            return;
        }

        log.info("开始同步数据库商品信息到meilisearch！");
        long start = System.currentTimeMillis();

        List<Goods> goodsList = goodsMapper.findAll(new Goods());

        List<GoodsVo> goodsVos = goodsList.stream().map(goods -> {
            GoodsVo goodsVo = MappingUtil.mapObject(goods, GoodsVo.class);
            goodsVo.setCategoryName(categoryMapper.findById(goods.getCategoryId()).getName());

            // 映射图片操作
            eventPublisher.publishEvent(new MapGoodsImageEvent(goods, goodsVo));
            // 商品卖家
            goodsVo.setSellerName(userMapper.findById(goods.getCreateBy()).getUsername());
            return goodsVo;
        }).collect(Collectors.toList());

        // 存在索引则删除
        if (meiliSearchUtil.getAllIndexes().stream().anyMatch(index -> "goods".equals(index.getUid()))) {
            meiliSearchUtil.deleteIndexAndDocuments("goods");
        }

        meiliSearchUtil.addDocument("goods", "id", JSONArray.toJSONString(goodsVos));

        log.info("同步结束！耗时：{} ms", System.currentTimeMillis() - start);
    }


}
